package com.session.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            //取得并输出用户提交的信息
            String msg = request.getParameter("msg");
            byte[] bytes = msg.getBytes(StandardCharsets.ISO_8859_1);
            // 对获得的字节数组进行解码 UTF-8
            msg = new String(bytes, StandardCharsets.UTF_8);

            out.print(msg);
            //输出水平线做为分隔以便更清楚地看到效果
            out.print("<hr />");
            //访问与当前请求相关联的会话对象，如果不存在，则创建一个
            HttpSession session = request.getSession();
            //获得会话对象的ID
            String sessionId = session.getId();
            //输出会话ID
            out.print(sessionId);
            //将用户提交的信息msg这个值（value）以myMsg这个名（key）存入会话对象
            session.setAttribute("myMsg", msg);
            //输出水平线做为分隔
            out.print("<hr />");
            //输出超级链接，注意href属性值的双引号""需要转义
            out.print("<a href=\"SessionServlet2\">链接到SessionServlet2</a>");            
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
